package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart

import com.bp.hearthealth.pulse.lnapps.bp_db.bp_heartrate.BpHeartRateBean
import com.bp.hearthealth.pulse.lnapps.bp_db.bp_heartrate.BpHeartRateDao
import com.bp.hearthealth.pulse.lnapps.bp_db.bp_project.BpDataBaseManager
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_network.BaseRepository
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.withContext

class BpHeartRateRepository(private val heartRateDao: BpHeartRateDao) : BaseRepository() {

    suspend fun updateAuthorize() = withContext(Dispatchers.IO){
        coroutineScope {
            BpDataBaseManager.getInstance().getUser()
                .updateIsFirstAuthorizePermission(Constants.USER_ID, false)
        }
    }

    suspend fun updateIsFirstDetection() = withContext(Dispatchers.IO) {
        coroutineScope {
            try {
                BpDataBaseManager.getInstance().getUser()
                    .updateIsFirstOpenGuide(Constants.USER_ID, false)
            } catch (e: Exception) {
                -1
            }
        }
    }

    suspend fun insertHeartRate(list: List<BpHeartRateBean>) = withContext(Dispatchers.IO) {
        coroutineScope {
            try {
                heartRateDao.insertHeartRateList(list).first().toLong()
            } catch (e: Exception) {
                LogUtil.e(e)
                null
            }
        }
    }

    suspend fun updateUnlocked(id: Long) = withContext(Dispatchers.IO) {
        coroutineScope {
            try {
                heartRateDao.updateUnlocked(id = id, unlocked = true)
            } catch (e: Exception) {
                LogUtil.e(e)
                -1
            }
        }
    }


    suspend fun loadHeartRateList() = withContext(Dispatchers.IO) {
        coroutineScope {
            heartRateDao.getHeartRatesListByUserId(userId = Constants.USER_ID)
        }
    }

    suspend fun deleteHeartRateById(id: Long) = withContext(Dispatchers.IO) {
        coroutineScope {
            heartRateDao.deleteHeartRateById(id = id)
        }
    }

    suspend fun inquireNum(id: Long) = withContext(Dispatchers.IO) {
        coroutineScope {
            heartRateDao.inquireNum(id = id)
        }
    }

    suspend fun getHeartRateBeanById(id: Long) = withContext(Dispatchers.IO) {
        coroutineScope {
            heartRateDao.getHeartRateBeanById(id = id)
        }
    }
}